import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';

interface User {
  id: string;
  username: string;
  email: string;
  role: string;
}

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (credentials: LoginCredentials) => Promise<void>;
  logout: () => void;
}

interface LoginCredentials {
  username: string;
  password: string;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Check localStorage for existing auth data on mount
    const storedUser = localStorage.getItem('db_console_user');
    const storedToken = localStorage.getItem('db_console_token');
    
    if (storedUser && storedToken) {
      try {
        const userData = JSON.parse(storedUser);
        setUser(userData);
      } catch (error) {
        console.error('Error parsing stored user data:', error);
        localStorage.removeItem('db_console_user');
        localStorage.removeItem('db_console_token');
      }
    }
    
    setIsLoading(false);
  }, []);

  const login = async (credentials: LoginCredentials): Promise<void> => {
    setIsLoading(true);
    
    try {
      // Check if we should use mock auth or real backend
      const dataSource = localStorage.getItem('dataSource') || 'mock';
      
      if (dataSource === 'backend') {
        // Real backend authentication
        const { AuthAPI } = await import('../api');
        const response = await AuthAPI.login(credentials);
        
        if (response.data && response.data.user && response.data.token) {
          const { user, token, refreshToken } = response.data;
          
          // Store in localStorage
          localStorage.setItem('db_console_user', JSON.stringify(user));
          localStorage.setItem('db_console_token', token);
          if (refreshToken) {
            localStorage.setItem('db_console_refresh_token', refreshToken);
          }
          
          setUser(user);
        } else {
          throw new Error('Invalid response from server');
        }
      } else {
        // Mock authentication logic
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        if (credentials.username === 'admin' && credentials.password === 'password') {
          const userData: User = {
            id: '1',
            username: credentials.username,
            email: 'admin@example.com',
            role: 'admin'
          };
          
          const token = 'mock-jwt-token-' + Date.now();
          
          // Store in localStorage
          localStorage.setItem('db_console_user', JSON.stringify(userData));
          localStorage.setItem('db_console_token', token);
          
          setUser(userData);
        } else {
          throw new Error('Invalid credentials');
        }
      }
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    } finally {
      setIsLoading(false);
    }
  };

  const logout = () => {
    setUser(null);
    localStorage.removeItem('db_console_user');
    localStorage.removeItem('db_console_token');
  };

  const value: AuthContextType = {
    user,
    isAuthenticated: !!user,
    isLoading,
    login,
    logout
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};